#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> 
#include <time.h>

int single(int* Array,int S){
	int temp = 0;
	int i;
	for( i = 0;i<S;++i){
		temp+=Array[i];
	}
	return temp;
} 

const int S = 320000000;
int* arr;

typedef struct{
	int first;
	int last;
	int result;
}MY_ARGS;

void* mysum(void* args){
	int i;
	int s=0;
	MY_ARGS* my_args = (MY_ARGS*) args;
	int first = my_args->first;
	int last = my_args->last;

	for(i=first;i<last;i++){
		s = s + arr[i];
	}
	my_args -> result = s;
	return NULL;
}

int main(){
	clock_t start,end;

	int i;
	arr = malloc(sizeof(int) * S);
	for(i=0;i<S;i++){
		if(i%2==0)
			arr[i]=i;
		else
			arr[i]=-i;
	}
	//  sigle thread
	int ans;
	start = clock();
	ans = single(arr,S);
	end = clock();
	printf("sum: %d\n",ans);
	printf("time:%d\n",end-start);
	// mul thread
 	start = clock();
 	int thread_num = 4;
 	pthread_t th[thread_num];
	MY_ARGS args[thread_num];

	int mid = S/thread_num;
	for(i=0;i<thread_num;i++){
		args[i].first=i*mid;
		args[i].last =(i+1)*mid;
		args[i].result=0;
	}
	
	for(i=0;i<thread_num;i++){
		pthread_create(&th[i],NULL,mysum,&args[i]);
	}
	
	for(i=0;i<thread_num;i++){
		pthread_join(th[i],NULL);
	}	
	ans=0;
	for(i=0;i<thread_num;i++){
		ans+= args[i].result;
	}	
	
	end =clock();

//	printf("sum: %d\n",args1.result + args2.result+args3.result+args4.result);
	printf("mul_sum: %d\n",ans);
	printf("time:%d\n",end-start);

	return 0;
}
